<template>
  <div class="divBox">
    <el-card class="box-card">
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch">
        <el-form-item label="menuName" prop="menuName">
          <el-input v-model="queryParams.name" placeholder="Please enter the menu name" clearable size="small" />
        </el-form-item>
        <el-form-item label="type" prop="menuType">
          <el-select v-model="queryParams.menuType" placeholder="type" clearable size="small">
            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">Query</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">Reset</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
            v-hasPermi="['platform:merchant:menu:add']">Add</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="info" plain icon="el-icon-sort" size="mini" @click="toggleExpandAll">Expand/Collapse</el-button>
        </el-col>
      </el-row>

      <el-table v-if="refreshTable" v-loading="listLoading" :data="menuList" row-key="id"
        :default-expand-all="isExpandAll" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        :header-cell-style="{ fontWeight: 'bold' }">
        <el-table-column prop="name" label="name" :show-overflow-tooltip="true" min-width="150"></el-table-column>
        <el-table-column prop="icon" label="icon" align="center" min-width="100">
          <template slot-scope="scope">
            <i :class="'el-icon-' + scope.row.icon" style="font-size: 20px" />
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="sort" min-width="60"></el-table-column>
        <el-table-column prop="perms" label="Permission flag" :show-overflow-tooltip="true" min-width="240"></el-table-column>
        <el-table-column prop="component" label="Component Path" :show-overflow-tooltip="true" min-width="200"></el-table-column>
        <el-table-column prop="isShow" label="state" min-width="80">
          <template slot-scope="scope">
            <el-tag :type="scope.row.isShow ? '' : 'danger'">{{ scope.row.isShow ? 'show' : 'hide' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="Creation time" align="center" prop="createTime">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="menuType" label="Type" min-width="80">
          <template slot-scope="scope">
            <span class="type_tag one" v-if="scope.row.menuType == 'M'">directory</span>
            <span class="type_tag two" v-else-if="scope.row.menuType == 'C'">menu</span>
            <span class="type_tag three" v-else type="info">button</span>
          </template>
        </el-table-column>
        <el-table-column label="operate" align="center" class-name="small-padding fixed-width" min-width="140">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
              v-hasPermi="['platform:merchant:menu:update', 'platform:merchant:menu:info']">update</el-button>
            <el-button size="mini" type="text" icon="el-icon-plus" @click="handleAdd(scope.row)"
              v-hasPermi="['platform:merchant:menu:add']">add</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
              v-hasPermi="['platform:merchant:menu:delete']">delete</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 添加或修改菜单对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="680px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-row>
            <el-col :span="24">
              <el-form-item label="Previous menu">
                <treeselect v-model="form.pid" :options="menuOptions" :normalizer="normalizer" :show-count="true"
                  placeholder="Select the previous menu" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="Menu Type" prop="menuType">
                <el-radio-group v-model="form.menuType">
                  <el-radio label="M"> directory</el-radio>
                  <el-radio label="C"> menu</el-radio>
                  <el-radio label="A"> button</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item v-if="form.menuType != 'A'" label="icon">
                <el-form-item>
                  <el-input placeholder="icon" v-model="form.icon">
                    <el-button slot="append" icon="el-icon-circle-plus-outline" @click="addIcon"></el-button>
                  </el-input>
                </el-form-item>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="menuName" prop="menuName">
                <el-input v-model="form.name" placeholder="Please enter the menu name" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="sort" prop="sort">
                <el-input-number v-model="form.sort" controls-position="right" :min="$constants.NUM_Range.min"
                  :max="$constants.NUM_Range.max" />
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="form.menuType !== 'A'">
              <el-form-item prop="component">
                <span slot="label">
                  <el-tooltip
                    content="Accessed component path, such as: `system/user/index`, by default in the `views` directory"
                    placement="top">
                    <i class="el-icon-question"></i>
                  </el-tooltip>
                  Component Path
                </span>
                <el-input v-model="form.component" placeholder="Please enter the component path" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item v-if="form.menuType != 'M'">
                <el-input v-model="form.perms" placeholder="Please enter the permission ID" maxlength="100" />
                <span slot="label">
                  <el-tooltip
                    content="Permission string defined in the controller，如：@PreAuthorize(`@ss.hasPermi('system:user:list')`)"
                    placement="top">
                    <i class="el-icon-question"></i>
                  </el-tooltip>
                  Permission Character
                </span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item>
                <span slot="label">
                  <el-tooltip
                    content="If you choose Hide, the route will not appear in the sidebar, but it can still be accessed."
                    placement="top">
                    <i class="el-icon-question"></i>
                  </el-tooltip>
                  Display Status
                </span>
                <el-radio-group v-model="form.isShow">
                  <el-radio v-for="item in showStatus" :key="item.value" :label="item.value">{{ item.label }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm"
            v-hasPermi="['platform:merchant:menu:add', 'platform:merchant:menu:update']">OK</el-button>
          <el-button @click="cancel">Cancel</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
  import {
    menuMerListApi,
    menuMerInfo,
    menuMerUpdate,
    menuMerAdd,
    menuMerDelete
  } from '@/api/merchant';
  import Treeselect from '@riophae/vue-treeselect';
  import '@riophae/vue-treeselect/dist/vue-treeselect.css';
  import {
    Debounce
  } from '@/utils/validate';
  export default {
    name: 'Menu',
    components: {
      Treeselect
    },
    data() {
      return {
        // 遮罩层
        listLoading: true,
        // 显示搜索条件
        showSearch: true,
        // 菜单表格树数据
        menuList: [],
        // 菜单树选项
        menuOptions: [],
        // 弹出层标题
        title: '',
        // 是否显示弹出层
        open: false,
        // 是否展开，默认全部折叠
        isExpandAll: false,
        // 重新渲染表格状态
        refreshTable: true,
        // 查询参数
        queryParams: {
          name: '',
          menuType: '',
        },
        // 表单参数
        form: {},
        //请求到的menu数据
        menuDataList: [],
        // 表单校验
        rules: {
          name: [{
            required: true,
            message: 'Menu name cannot be empty',
            trigger: 'blur'
          }],
          sort: [{
            required: true,
            message: 'Menu order cannot be empty',
            trigger: 'blur'
          }],
        },
        statusOptions: [{
            value: 'M',
            label: 'Directory'
          },
          {
            value: 'C',
            label: 'Menu'
          },
          {
            value: 'A',
            label: 'Button'
          },
        ],
        showStatus: [{
            label: 'Show',
            value: true
          },
          {
            label: 'Hide',
            value: false
          },
        ],
      };
    },
    created() {
      this.getList();
    },
    methods: {
      // 点击图标
      addIcon() {
        const _this = this;
        _this.$modalIcon(function(icon) {
          _this.form.icon = icon;
        });
      },
      /** 查询菜单列表 */
      getList() {
        this.listLoading = true;
        menuMerListApi(this.queryParams).then((res) => {
          let obj = {},
            menuList = [];
          res.forEach((item) => {
            obj = item;
            obj.parentId = item.pid;
            obj.children = [];
            menuList.push(obj);
          });
          this.menuDataList = menuList;
          this.menuList = this.handleTree(menuList, 'menuId');
          this.getTreeselect();
          this.listLoading = false;
        });
      },
      /** 转换菜单数据结构 */
      normalizer(node) {
        if (node.children && !node.children.length) {
          delete node.children;
        }
        return {
          id: node.id ? node.id : 0,
          label: node.name ? node.name : 'Main Directory',
          children: node.children,
        };
      },
      /** 查询菜单下拉树结构 */
      getTreeselect() {
        this.menuOptions = [];
        const menu = {
          menuId: 0,
          menuName: 'main category',
          children: []
        };
        menu.children = this.handleTree(this.menuDataList, 'menuId');
        this.menuOptions.push(menu);
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          menuId: '',
          parentId: 0,
          name: '',
          icon: '',
          menuType: 'M',
          sort: 0,
          isShow: true,
          component: '',
          perms: '',
        };
        this.resetForm('form');
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        (this.queryParams = {
          name: '',
          menuType: ''
        }), this.handleQuery();
      },
      /** 新增按钮操作 */
      handleAdd(row) {
        this.reset();
        if (row != null && row.id) {
          this.form.pid = row.id;
        } else {
          this.form.pid = 0;
        }
        this.open = true;
        this.title = 'Add a menu';
      },
      /** 展开/折叠操作 */
      toggleExpandAll() {
        this.refreshTable = false;
        this.isExpandAll = !this.isExpandAll;
        this.$nextTick(() => {
          this.refreshTable = true;
        });
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
        });
        this.reset();
        menuMerInfo(row.id).then((response) => {
          this.form = response;
          this.open = true;
          this.title = 'Modify Menu';
          loading.close();
        });
      },
      /** 提交按钮 */
      submitForm: Debounce(function() {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            if (this.form.id != undefined) {
              menuMerUpdate(this.form).then((response) => {
                this.$modal.msgSuccess('Modification successful');
                this.open = false;
                this.getList();
              });
            } else {
              menuMerAdd(this.form).then((response) => {
                this.$modal.msgSuccess('Added successfully');
                this.open = false;
                this.getList();
              });
            }
          }
        });
      }),
      /** 删除按钮操作 */
      handleDelete(row) {
        this.$modal
          .confirm('Are you sure to delete the data item named "' + row.name + '"?')
          .then(function() {
            return menuMerDelete(row.id);
          })
          .then(() => {
            this.getList();
            this.$modal.msgSuccess('Deleted successfully');
          })
          .catch(() => {});
      },
    },
  };
</script>
<style lang="scss">
  .mb8 {
    margin-bottom: 8px;
  }

  .type_tag {
    display: inline-block;
    height: 32px;
    padding: 0 10px;
    line-height: 30px;
    font-size: 12px;
    border-radius: 4px;
    box-sizing: border-box;
    white-space: nowrap;
  }

  .two {
    background: rgba(239, 156, 32, 0.1);
    color: rgba(239, 156, 32, 1);
  }

  .one {
    background: rgba(75, 202, 213, 0.1);
    color: rgba(75, 202, 213, 1);
  }

  .three {
    color: rgba(120, 128, 160, 1);
    background: rgba(120, 128, 160, 0.1);
  }
</style>
